<?php

declare(strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Model\Model;
use Hyperf\DbConnection\Db;

/**
 * 动态点赞
 */
class MomentLike extends Model
{
    protected $table = 'moment_like';

    protected $fillable = [
        'user_id', 'moment_id', 'flag'
    ];

    public function userInfo()
    {
        return $this->belongsTo(UserProfile::class, 'user_id', 'user_id');
    }

    /**
     * 添加点赞记录
     */
    static function addLike($userId = 0, $momentId = 0, $flag = 1)
    {
        $ret = self::updateOrCreate([
            'user_id' => $userId,
            'moment_id' => $momentId,
        ], [
            'user_id' => $userId,
            'moment_id' => $momentId,
            'flag' => $flag
        ]);
        return $ret ? 1 : 0;
    }

    /**
     * 用户是否点赞动态
     */
    static function check($userId = 0, $momentId = 0)
    {
        $where = ['user_id' => $userId, 'moment_id' => $momentId, 'flag' => 1];
        return self::where($where)->count() ? 1 : 0;
    }

    /**
     * 动态点赞列表
     */
    static function getList($momentId = 0)
    {
        $where = [
            'moment_id' => $momentId,
            'flag' => 1,
        ];
        return self::where($where)->orderBy('id', 'desc')->get();
    }

    /**
     * 列表元素结构
     */
    static function buildItem($item)
    {
        return [
            "user_id" => $item->user_id,
            "nick_name" => $item->userInfo->nick_name,
            "avatar" => UserProfile::buildAvatar($item->userInfo->avatar),
            "content" => "点赞了动态",
            "msg_time" => (string)$item->created_at
        ];
    }

    /**
     * 用户点赞列表
     */
    static function getUserLikeList($userId = 0)
    {
        $where = [
            'moment.user_id' => $userId,
            'moment_like.flag' => 1,
        ];
        $fields = ['moment_like.created_at as created_at', 'moment_like.user_id as user_id', 'moment_id'];
        $data = Db::table('moment')->join('moment_like', function ($join) use ($userId) {
            $join->on('moment_like.moment_id', '=', 'moment.id');
        })->where($where)->orderBy('moment_like.id', 'desc')->select($fields)->get()->toArray();
        return $data;
    }
}
